package com.samuel.blog.utils;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.samuel.blog.constant.CommonConstant;

/**
 * lucene 工具类
 *
 * @author kaiji
 */
public class LuceneUtils {

	private static final Logger logger = Logger.getLogger(LuceneUtils.class);
	private static IndexWriter indexWrite = null;
	private static IndexSearcher indexSearcher = null;
	
	public static IndexWriter getIndexWriter() {
		try {
			Directory dir = FSDirectory.open(Paths.get(CommonConstant.LUCENE_SAVE));
			Analyzer analyzer = new SmartChineseAnalyzer();
			IndexWriterConfig config = new IndexWriterConfig(analyzer);
			indexWrite = new IndexWriter(dir, config);
			indexWrite.commit();
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return indexWrite;
	}
	
	public static IndexSearcher getIndexSearcher() {
		try {
			Directory dir = FSDirectory.open(Paths.get(CommonConstant.LUCENE_SAVE));
			IndexReader reader = DirectoryReader.open(dir);
			indexSearcher = new IndexSearcher(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return indexSearcher;
	}
	
	
}
